#!/usr/bin/env python

import re
import component
import component.restclient

class Measurement(object):

    host = None
    device = None
    channels = None
    
    def __init__(self):
        self.channels = []
    
    def bulk(self, host=None, proxyInfo=None):
        host = host if host else self.host
        url = 'http://%s/api/measurement/bulk' % host
        
        params = {'Measurement[deviceSequence]': self.device}
        for i, channel in enumerate(self.channels):
            s = 'MeasurementChannel[%d]' % i
            params['%s[channelSequence]' % s] = channel.sequence
            params['%s[value]' % s] = channel.value
        return component.restclient.POST(url, params, proxy_info=proxyInfo)
        
    @classmethod
    def parse(cls, line):
        """Parse string
        
        Args:
            line: string that contains ':#,#,#,#,#,#,#,#,#'. May contains more
                  than one instance.
            
        Returns:
            A list of Measurement class or empty list.
        """
        
        pattern = r':(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)'
        data = re.findall(pattern, line)
        
        measurements = []
        for datum in data:
            measurement = cls()
            measurement.device = int(datum[0])
            for i in range(1, 9):
                channel = component.Namespace()
                channel.sequence = i
                channel.value = int(datum[i])
                measurement.channels.append(channel)
            measurements.append(measurement)
        return measurements